/*
 * Copyright (c) 2010 Mathias Garbe <code@mathias-garbe.de>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include "main.hpp"

using namespace std;

std::vector<std::string> &std::split(const std::string &s, char delim, std::vector<std::string> &elems) {
	std::stringstream ss(s);
	std::string item;
	while(std::getline(ss, item, delim)) {
		elems.push_back(item);
	}
	return elems;
}

std::vector<std::string> std::split(const std::string &s, char delim) {
	std::vector<std::string> elems;
	return split(s, delim, elems);
}

bool FileExists(const char *path)
{
	if(FILE* file = fopen(path, "r"))
	{
		fclose(file);
		return true;
	}
	return false;
}

#ifdef _DEBUG
// enables a console for debug output
void enableConsole()
{
    AllocConsole();

    CONSOLE_SCREEN_BUFFER_INFO conInfo;
    GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &conInfo);
    conInfo.dwSize.Y = 1000;
    SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), conInfo.dwSize);

    // redirect stdin
    long stdHnd = (long)GetStdHandle(STD_INPUT_HANDLE);
    long conHnd = _open_osfhandle(stdHnd, _O_TEXT);

    FILE *fp = _fdopen(conHnd, "r");
    *stdin = *fp;
    setvbuf(stdin, NULL, _IONBF, 0);

    // redirect stdout
    stdHnd = (long)GetStdHandle(STD_OUTPUT_HANDLE);
    conHnd = _open_osfhandle(stdHnd, _O_TEXT);

    fp = _fdopen(conHnd, "w");
    *stdout = *fp;
    setvbuf(stdout, NULL, _IONBF, 0);

    // redirect stderr
    stdHnd = (long)GetStdHandle(STD_ERROR_HANDLE);
    conHnd = _open_osfhandle(stdHnd, _O_TEXT);

    fp = _fdopen(conHnd, "w");
    *stderr = *fp;
    setvbuf(stderr, NULL, _IONBF, 0);

    std::ios::sync_with_stdio();
}
#endif

int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    #ifdef _DEBUG
        enableConsole();
        std::cout << "LegacyUpdate started..." << std::endl;
    #endif

    InitCommonControls();

    INITCOMMONCONTROLSEX iCCex;
    iCCex.dwSize = sizeof(INITCOMMONCONTROLSEX);
    iCCex.dwICC = ICC_BAR_CLASSES | ICC_PROGRESS_CLASS | ICC_TAB_CLASSES | ICC_LISTVIEW_CLASSES;
    InitCommonControlsEx(&iCCex);

    // Initialize hInstance holder
    WinAPI::hInstance(hInstance);

    // Update to newest version
    Update *update = new Update();

    delete update;

    return 0;
}
